package com.huangpf.util.excelUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;


/**
 * Created by huangpf on 2016/8/31.
 */
public class ExcelUtil {
    private static final String dlFilePath = "D:\\MyJob\\Project\\Maven\\com\\huangpf\\util\\src\\main\\java\\com\\huangpf\\util\\excelUtil";
    private static final String urlPath = "";

    /**
     * 导出excel
     * @param xmlPath
     * @param fileName
     * @param list
     * @return
     */
    public static String exportExcel(String xmlPath, String fileName, List list){
        Workbook wb = null;
        Document document = null;
        try {
            if (fileName.endsWith(".xlsx")){
                wb = new XSSFWorkbook();
            } else if (fileName.endsWith(".xls")){
                wb = new HSSFWorkbook();
            } else {
                wb = new XSSFWorkbook();
                fileName = fileName + ".xlsx";
            }


            SAXReader reader = new SAXReader();
            document = reader.read(new FileInputStream(xmlPath));
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }

        return exportExcel(wb, document, fileName, list); // 返回url
    }

    /**
     * 导出excel
     * @param wb
     * @param document
     * @param fileName
     * @param list
     * @return
     */
    public static String exportExcel(Workbook wb, Document document,String fileName, List list){
        ExcelGen excelGen = new ExcelGen(wb, new ExcelXml(document), list);
        wb = excelGen.getWb();

        // 生成文件
        File dir = new File(dlFilePath);
        if (!dir.exists()){
            dir.mkdir();
        }
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(dlFilePath + "/" + fileName);
            wb.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOut != null){
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return urlPath + "/" + fileName;
    }

}
